package com.demo.borrow;

import com.demo.common.model.Borrow;
import com.demo.common.model.Readers;
import com.demo.common.model.User;
import com.demo.common.util.StringUtil;
import com.demo.readers.ReaderService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

/**
 * 本 com.demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * 所有 sql 与业务逻辑写在 Service 中，不要放在 Model 中，更不
 * 要放在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
@Before(BorrowInterceptor.class)
public class BorrowController extends Controller {
	
	@Inject
	BorrowService service;

	@Inject
	ReaderService readerService;

	//加载借书管理页面
	public void index() {
		Kv cond=Kv.create();
		if(StrKit.notBlank(getPara("orderno"))){
			cond.set("a.orderno",getPara("orderno"));
		}
		if(StrKit.notBlank(getPara("readerno"))){
			cond.set("c.readerno",getPara("readerno"));
		}
		if(StrKit.notBlank(getPara("readername"))){
			cond.set("c.readername",getPara("readername"));
		}
		setAttr("borrowPage", service.paginate(getParaToInt(0, 1), 10,Kv.by("cond",cond)));
		render("borrow.html");
	}

    //删除借书订单
	public void delete() {
		service.deleteById(getParaToInt());
		redirect("/borrow");
	}

	//还书
	public void back(){
       Borrow borrow=new Borrow();
       borrow.setId(getParaToInt());
       borrow.setIsback(1);
       borrow.setUpdatedate(StringUtil.strToTimeStamp());
       borrow.update();
       redirect("/borrow");
	}

	//借书
	public void save(Record param){
		int bookId=Integer.parseInt(getPara("bookid"));
		String readerNo=getPara("readerno");
		int bookNum=Integer.parseInt(getPara("booknum"));
		Readers readers=this.readerService.findFirstByReaderNo(readerNo);
		Borrow borrow=new Borrow();
		borrow.setBookid(bookId);
		borrow.setOrderno(StringUtil.getOrderNo());
		borrow.setIsback(0);
		borrow.setBooknum(bookNum);
		borrow.setReaderid(readers.getId());
		borrow.setCreatedate(StringUtil.strToTimeStamp());
		borrow.setUpdatedate(borrow.getCreatedate());
		borrow.save();
		redirect("/borrow");
	}
}


